<?php


namespace app\plugin\controller\merchant;


use app\common\controller\AppCommon;
use app\plugin\controller\merchant\com\MerchantManager;
use app\service\DiyLog;
use app\service\Page;
use app\service\Uploader;

class Manager extends MerchantManager
{
    public function index($recycle = false)
    {
        $where = [];
        $sort = !empty($this->param['sort']) ? trim($this->param['sort']) : '';
        $status = isset($this->param['status']) && is_numeric($this->param['status']) ? intval($this->param['status']) : '';
        $categoryId = !empty($this->param['category_id']) ? intval($this->param['category_id']) : 0;
        $keyword = !empty($this->param['keyword']) ? trim($this->param['keyword']) : '';
        $orderBy = 'id desc';
        if ($sort == 'id_asc') {
            $orderBy = 'id asc';
        } elseif ($sort == 'id_desc') {
            $orderBy = 'id desc';
        } elseif ($sort == 'price_asc') {
            $orderBy = 'price asc';
        } elseif ($sort == 'price_desc') {
            $orderBy = 'price desc';
        } elseif ($sort == 'sale_asc') {
            $orderBy = 'sale asc';
        } elseif ($sort == 'sale_desc') {
            $orderBy = 'sale desc';
        } elseif ($sort == 'stock_asc') {
            $orderBy = 'stock asc';
        } elseif ($sort == 'stock_desc') {
            $orderBy = 'stock desc';
        }
        if ($status == '0' || $status == 1) {
            $where['status'] = $status;
        } elseif ($status == -1) {
            $where['stock'] = 0;
        }
        if (!empty($categoryId)) {
            $where['category_id'] = $categoryId;
        }
        if (!empty($keyword)) {
            $where['title'] = ['like', '%' . $keyword . '%'];
        }
        if ($recycle) {
            $where['is_del'] = 1;
        } else {
            $where['is_del'] = 0;
        }

        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $pageSize = 10;

        $where['store_num'] = $this->store_num;

        $data = AppCommon::data_list('goods', $where, $page . ',' . $pageSize, 'title,thumb,id,market_price,price,stock,stock_locked,status,sale,add_time', $orderBy);


        $total = AppCommon::data_count('goods', $where);
        $category = AppCommon::data_list_nopage('goods_category', ['status' => 1]);
        if ($category) {
            $this->assign('category', tree($category, 'category_id', 'parent_id', 'subcat'));
        }
        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));
        $this->assign('data', $data);
        if ($recycle) {
            $tpl = 'recycle';
        } else {
            $tpl = 'index';
        }
        return $this->fetch($tpl);
    }


    public function form()
    {
        if (empty($this->store_num)) {
            return $this->error('请先配置店铺', url('/plugin/' . $this->tag . '.manager/store_info'), '', 2);
        }
        $id = !empty($this->param['id']) ? intval($this->param['id']) : 0;
        if ($id) {
            $goods = AppCommon::data_get('goods', ['id' => $id, 'store_num' => $this->store_num]);
            if (!empty($goods)) {
                $goods['banners'] = json_decode($goods['banners'], true);
                $goods['content'] = htmlspecialchars_decode($goods['content']);
                $this->assign('goods', $goods);
            }

        }

        $category = AppCommon::data_list_nopage('goods_category', ['status' => 1]);
        if ($category) {
            $this->assign('category', tree($category, 'category_id', 'parent_id', 'subcat'));
        }
        return $this->fetch();
    }

    //商品操作
    public function goods_action()
    {
        $merchantCheck = $this->check_account();
        if ($merchantCheck['code'] <> 0) {
            data_return($merchantCheck['msg'], $merchantCheck['code']);
        }
        $id = !empty($this->param['id']) ? intval($this->param['id']) : 0;
        $ac = !empty($this->param['ac']) ? trim($this->param['ac']) : '';
        if (!empty($id)) {
            $goods = AppCommon::data_get('goods', ['id' => intval($id), 'store_num' => $this->store_num]);
            if (empty($goods)) {
                data_return('商品已不存在', -1);
            }
            //放到回收站
            if ($ac == 'recycle') {
                AppCommon::data_update('goods', ['id' => $goods['id']], ['is_del' => 1, 'status' => 0]);
                data_return('已移入回收站，可以在回收站中恢复');
            } elseif ($ac == 'copy') {
                $data = [
                    'title' => 'copy_' . $goods['title'],
                    'goods_desc' => trim($goods['goods_desc']),
                    'banners' => $goods['banners'],
                    'content' => $goods['content'],
                    'thumb' => $goods['thumb'],
                    'market_price' => floatval($goods['market_price']),
                    'price' => floatval($goods['price']),
                    'stock' => intval($goods['stock']),
                    'category_id' => intval($goods['category_id']),
                    'status' => 0,
                    'is_top' => $goods['is_top'],
                    'store_num' => $goods['store_num'],
                ];
                $data['add_time'] = time();
                $res = AppCommon::data_add('goods', $data);
                data_return('复制成功');
            }
        }


        $rule = [
            ['type' => 'length', 'key' => 'title', 'rule' => '2,80', 'msg' => '商品名称2~80字符',],
            ['type' => 'empty', 'key' => 'category_id', 'rule' => '', 'msg' => '请选择分类',],
            ['type' => 'empty', 'key' => 'thumb', 'rule' => '', 'msg' => '请选择封面图',],
            ['type' => 'min', 'key' => 'price', 'rule' => '0.01', 'msg' => '请输入商品价格',],
            ['type' => 'min', 'key' => 'market_price', 'rule' => '0.01', 'msg' => '市场价未设置',],
            ['type' => 'empty', 'key' => 'stock', 'rule' => '', 'msg' => '商品库存未设置',],
            ['type' => 'empty', 'key' => 'banners', 'rule' => '', 'msg' => '轮播图未选择图片',],
        ];
        $check = check_param($this->param, $rule);
        if ($check['code'] <> 0) {
            data_return($check['msg'], $check['code']);
        }
        if (count($this->param['banners']) > 10) {
            data_return('轮播图不能超过10张', -1);
        }


        $data = [
            'title' => trim($this->param['title']),
            'goods_desc' => trim($this->param['desc']),
            'banners' => json_encode($this->param['banners']),
            'content' => $this->param['content'],
            'thumb' => trim($this->param['thumb']),
            'market_price' => floatval($this->param['market_price']),
            'price' => floatval($this->param['price']),
            'stock' => intval($this->param['stock']),
            'category_id' => intval($this->param['category_id']),
            'status' => !empty($this->param['status']) ? 1 : 0,
            'banner2detail' => !empty($this->param['banner2detail']) ? 1 : 0,
            'store_num' => $this->store_num,
        ];
        if (!empty($id)) {
            $res = AppCommon::data_update('goods', ['id' => intval($id)], $data);
        } else {
            $data['add_time'] = time();
            $res = AppCommon::data_add('goods', $data);
        }
        data_return('操作完成', 0, [
            'res' => $res
        ]);
    }

    //上传图片
    public function upload_image()
    {
        $merchantCheck = $this->check_account();
        if ($merchantCheck['code'] <> 0) {
            data_return($merchantCheck['msg'], $merchantCheck['code']);
        }
        if (empty($this->param['fileKey'])) {
            data_return('参数有误', -1);
        }
        if (empty($this->param['from'])) {
            data_return('参数有误', -1);
        }
        $tool_form = !empty($this->param['tool_form']) ? trim($this->param['tool_form']) : '';

        if (empty($_FILES[$this->param['fileKey']])) {
            data_return('请先选择文件', -1);
        }

        $toPath = config('upload')['defaultPath'] . trim($this->param['from']) . '/';
        //拼接全连接
        $returnUrl = str_replace(PUBLIC_PATH, URL_WEB, $toPath);
        $res = Uploader::start_upload($this->param['fileKey'], $toPath, $returnUrl, '', 1);
        if ($res['code'] == 0) {
            //parent::add_admin_log(['title' => '上传文件', 'content' => $res['data']]);
        }

        data_return(
            $res['code'] == 0 ? 'ok' : $res['msg'],
            $res['code'],
            [
                'url' => isset($res['data']) ? $res['data'] : '',
            ]
        );
    }


    public function urls()
    {
        $data = [
            ['name' => '商户注册', 'url' => URL_WEB . trim(url('/plugin/' . $this->tag . '.account/reg'), '/')],
            ['name' => '商户登录', 'url' => URL_WEB . trim(url('/plugin/' . $this->tag . '.account/login'), '/')],
            ['name' => '商户后台', 'url' => URL_WEB . trim(url('/plugin/' . $this->tag . '.manager/index'), '/')],
            ['name' => '店铺首页', 'url' => URL_WEB . trim(url('/mall/goods/pro_list'), '/') . '?store_num=' . $this->store_num],
        ];
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function store_info()
    {
        $data = AppCommon::data_get('stores', ['merchant_uid' => $this->m_uid]);
        if (!empty($data)) {
            $this->assign('data', $data);
        }
        return $this->fetch();
    }


    public function store_action()
    {
        $merchantCheck = $this->check_account();
        if ($merchantCheck['code'] <> 0) {
            data_return($merchantCheck['msg'], $merchantCheck['code']);
        }
        if (empty($this->param['store_name'])) {
            data_return('店铺名称必填', -1);
        }
        $data = AppCommon::data_get('stores', ['merchant_uid' => $this->m_uid]);
        $upData = [
            'store_name' => trim($this->param['store_name']),
            'store_logo' => trim($this->param['img']),
            'up_time' => time(),
            'status' => !empty($this->param['status']) ? 1 : -1,
        ];
        if (empty($data)) {
            $upData['add_time'] = time();
            $upData['merchant_uid'] = $this->m_uid;

            $upData['is_check'] = 1;//默认已通过
            $upData['store_num'] = getNumberCode(6);
            while (true) {
                $hasC = AppCommon::data_get('stores', ['store_num' => $upData['store_num']], 'id');
                if (empty($hasC['id'])) {
                    break;
                }
                $upData['store_num'] = getNumberCode(6);
            }

            AppCommon::data_add('stores', $upData);
        } else {
            AppCommon::data_update('stores', ['id' => $data['id']], $upData);
        }

        data_return();
    }

    public function setting()
    {
        return $this->error('暂无需配置');
    }

    public function account()
    {
        $data = AppCommon::data_get('plugin_merchant', ['uid' => $this->m_uid]);
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function account_action()
    {
        if (!IS_AJAX) {
            return $this->error('非法操作');
        }
        $rule = [
            ['type' => 'length', 'key' => 'user_name', 'rule' => '2,32', 'msg' => '昵称1~32字符',],
        ];
        $check = check_param($this->param, $rule);
        if ($check['code'] <> 0) {
            data_return($check['msg'], $check['code']);
        }

        //修改或者设置密码
        if (!empty($this->param['pwd1'])) {
            if (strlen($this->param['pwd1']) < 6) {
                data_return('密码不够安全,请输入6位数以上', -1);
            }
            if ($this->param['pwd1'] !== $this->param['pwd2']) {
                data_return('两次密码不一样', -1);
            }
        }
        $baseData = [
            'user_name' => trim($this->param['user_name']),
            'up_time' => time(),
        ];
        if (!empty($this->param['pwd1'])) {
            $salt = get_random(10, false);
            $pwd = md5($this->param['pwd1'] . $salt);
            $baseData = array_merge($baseData, [
                'pwd' => $pwd,
                'salt' => $salt,
            ]);
        }

        AppCommon::data_update('plugin_merchant', ['uid' => $this->m_uid], $baseData);

        data_return('操作成功');
    }

    //回收站
    public function recycle()
    {
        return $this->index(true);
    }

    //回收站操作
    public function recycle_action()
    {
        if (!IS_AJAX) {
            data_return('非法操作', -1);
        }
        $id = !empty($this->param['id']) ? intval($this->param['id']) : 0;
        if (empty($id)) {
            data_return('参数有误', -1);
        }
        $goods = AppCommon::data_get('goods', ['id' => intval($id), 'store_num' => $this->store_num]);
        if (empty($goods)) {
            data_return('商品已不存在', -1);
        }
        $ac = !empty($this->param['ac']) ? $this->param['ac'] : '';
        //完全移除
        if ($ac == 'del') {
            AppCommon::data_del('goods', ['id' => $goods['id']]);
            DiyLog::file($goods, 'del_goods_' . date('Ymd') . '.log');
            data_return('删除成功', 0);
        } elseif ($ac == 'restore') {
            //恢复
            AppCommon::data_update('goods', ['id' => $goods['id']], ['is_del' => 0]);
            data_return('恢复成功');
        }
        data_return('未知操作', -1);
    }

}